package com.flame.workflow.re.service;

import java.util.List;

import com.flame.core.id.IdWorker;
import com.flame.workflow.exception.WorkflowExcetionMessage;
import com.flame.workflow.exception.WorkflowRuntimeException;
import com.flame.workflow.re.controller.vo.ModelVo;
import com.flame.workflow.re.entity.Deployment;
import com.flame.workflow.re.entity.Model;
import com.flame.workflow.re.mapper.DeploymentMapper;
import com.flame.workflow.re.mapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * flame_workflow_re_model 流程模型定义表
 *
 * @author 吴欣童
 * @since 2023-05-04 19:54:59
 */
@Service
public class ModelService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private DeploymentMapper deploymentMapper;

    public List<Model> pageModel(ModelVo modelVo) {
        return modelMapper.page(modelVo);
    }

    public void addModel(Model model) {
        Model dbModel = modelMapper.findById(model.getModelId(), model.getModelVersion());
        if (dbModel != null) {
            throw new WorkflowRuntimeException(WorkflowExcetionMessage.MODEL_EXIST);
        }
        model.setModelId(idWorker.nextId());
        model.setModelVersion(1);
        modelMapper.insert(model);
    }

    public void updateModel(Model model) {
        modelMapper.updateById(model);
    }

    public void deleteModel(Model model) {
        Deployment deployment = deploymentMapper.findById(model.getModelId());
        if (ObjectUtils.isEmpty(deployment)) {
            modelMapper.deleteModel(model.getModelId());
            return;
        }
        throw new WorkflowRuntimeException(WorkflowExcetionMessage.DELETE_FAILED_MODEL_NOT_UNACTIVE);
    }

    public Model getModel(Long modelId, Integer modelVersion) {
        return modelMapper.findById(modelId, modelVersion);
    }

    public void maintainModel(Model model) {
        Model dbModel = modelMapper.findById(model.getModelId(), model.getModelVersion());
        if (dbModel != null) {
            modelMapper.updateById(model);
        } else {
            modelMapper.insert(model);
        }
    }
}
